<?php

/**
 * @file
 * Admin page callbacks for the newmodule module.
 */

/**
 * Show list of all administered sites.
 */
function multisite_sites_list() {
  //Create temporary storage for site sizes
  db_query_temporary("SELECT m.bid, m.base, m.created, 0 as tables_size, 0 as files_size FROM {multisite} m", 'tmp_multisite');
  
  //Populate temporary table with actual 'files' directory sizes
  //and tables sizes
  $result = db_query('SELECT * FROM {multisite}'); 
  while($site = db_fetch_object($result)) {
    $files_dir   = mutil_site_base_to_dirname($site->base) . '/files';
    $files_size  = mutil_dirsize_recursive($files_dir);
    $tables_size = mutil_tables_size(mutil_create_private_prefix($site->base));
    db_query("UPDATE tmp_multisite SET files_size = %d , tables_size = %d WHERE bid = %d", $files_size, $tables_size, $site->bid);
  }
  
  $header = array (
    array('data' => t('Base'),    'field' => 'base'),
    array('data' => t('Created'), 'field' => 'created', 'sort' => 'desc'),
    array('data' => t('Tables'),  'field' => 'tables_size'),
    array('data' => t('Files'),   'field' => 'files_size'),
    array('data' => t('Total'),   'field' => 'total_size'),
    array('data' => t('Operations')),
  );

  $result = pager_query("SELECT *, (tables_size + files_size) as total_size FROM tmp_multisite" . tablesort_sql($header), 50);
  
  while ($site = db_fetch_object($result)) {
    $rows[] = array('data' =>
      array (
        l($site->base, "http://" . $site->base),
        format_date($site->created, 'small'),
        mutil_format_size($site->tables_size),
        mutil_format_size($site->files_size),
        mutil_format_size($site->total_size),
        ($site->bid != TEMPLATE_BID && $site->bid != AGGREGATOR_BID)
          ? l(t('Delete'), 'admin/build/multisite/' . $site->bid . '/delete')
          : ''
      ),
    );
  }
  
  $output .= theme('table', $header, $rows);
  $output .= theme('pager', NULL, 50);

  return $output;
}

/**
 * New site form
 */
function multisite_add_site_form() {
  $form['base'] = array (
    '#type' => 'textfield',
    '#title' => t('Site path'),
    '#maxlength' => 128,
    '#description' => t('New site name. For example <strong>%example</strong>. Do not use %wrong_example this alias will created automatically.', array('%example' => 'newsite.' . mutil_aggregator_base(), '%wrong_example' => mutil_aggregator_base() . '/newsite')),
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Create site'),
  );
      
  return $form;
}

/**
 * Check base for correctnes
 */
function multisite_add_site_form_validate($form, &$form_state) {
  //Quick check is domain name correct
  if (!preg_match('@^(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$@i', $form_state['values']['base'])) {
    form_set_error('base', t('Invalid domain name'));
  }
  
  //Is this site already exists
  if (db_result(db_query("SELECT COUNT(*) FROM {multisite} WHERE base = '%s'", $form_state['values']['base']))){
    form_set_error('base', t('Site <strong>%base</strong> already exists', array('%base' => $form_state['values']['base'])));
  }
}

/**
 * Check base for correctnes
 */
function multisite_add_site_form_submit($form, &$form_state) {
  multisite_create_site($form_state['values']['base']);
  drupal_set_message(l($form_state['values']['base'], 'http://' . $form_state['values']['base']) . ' ' . t('created successfully.'));
}

/**
 * Delete site menu handler
 */
function multisite_delete_site_handler($site) {
  //We wan't delete this sites
  if ($site->bid == TEMPLATE_BID || $site->bid == AGGREGATOR_BID) {
    drupal_access_denied();
    return;
  }
  
  return drupal_get_form('multisite_delete_site_confirm', $site);
}

/**
 * Site deletion confirmation dialog
 */
function multisite_delete_site_confirm(&$form_state, $site) {

  $form['#site'] = $site;
  $caption .= '<p>'. t('The site %base, all content on the site and site private files will be deleted.', array('%base' => $site->base)) . '</p>';
  $caption .= '<p>'. t('This action cannot be undone.') .'</p>';

  return confirm_form (
    $form,
    t('Are you sure you want to delete the site?'),
    'admin/build/multisite', 
    $caption,
    t('Delete')
  );
}


/**
 * Delete a site
 */
function multisite_delete_site_confirm_submit($form, &$form_state) {
  $site = $form['#site'];
  $form_state['redirect'] = 'admin/build/multisite';
  
  multisite_delete($site->bid);
  drupal_set_message(t('Site %base deleted.', array('%base' => $site->base)));
}








